<template>
  <div>
    <!-- 数据分析 -->
    <el-radio-group
      v-model="analyseId"
      class="mb-[0.5rem]"
      @change="handleChangeAnalyse"
    >
      <el-radio-button label="设备分析" :value="1" />
      <el-radio-button label="AI" :value="2" />
      <el-radio-button label="手动" :value="3" />
    </el-radio-group>
    <!-- 1.设备分析 -->
    <!-- 2.AI分析 -->
    <!-- 3.手动分析 -->

    <el-scrollbar style="height: calc(100vh - 12rem)">
      <!-- 设备分析 -->
      <DataAnalyseOdOs
        title="OD/右眼"
        capName="Right"
        lowerName="right"
        v-show="analyseId == 1"
        @updateText="updateText"
      />
      <DataAnalyseOdOs
        title="OS/左眼"
        capName="Left"
        lowerName="left"
        v-show="analyseId == 1"
        @updateText="updateText"
      />

      <!-- ai分析 -->
      <el-input
        v-model="ai_result"
        type="textarea"
        placeholder="请点击下方按钮获取内容"
        :show-word-limit="true"
        :autosize="{
          minRows: 21,
          maxRows: 25,
        }"
        v-if="analyseId === 2"
        readonly
        @click="ElMessage.info('AI分析禁止手动编辑')"
      />
      <div class="w-full flex justify-between mt-2" v-if="analyseId === 2">
        <el-button
          type="danger"
          class="w-[30%]"
          icon="Close"
          @click="handleCancelUse"
          >清空</el-button
        >
        <el-button
          type="primary"
          class="w-[65%]"
          icon="Check"
          @click="handleCreateUseAiResult"
          >使用AI</el-button
        >
      </div>

      <!-- 手动分析 -->
      <el-input
        v-model="edit_result"
        type="textarea"
        placeholder="请输入内容"
        :show-word-limit="true"
        :autosize="{
          minRows: 21,
          maxRows: 25,
        }"
        v-if="analyseId === 3"
      />
      <div class="w-full flex justify-between mt-2" v-if="analyseId === 3">
        <el-button
          type="danger"
          class="w-[30%]"
          icon="Close"
          @click="handleEditRemove"
          >清空</el-button
        >
        <el-button
          type="primary"
          class="w-[65%]"
          icon="Check"
          @click="handleEditSubmit"
          >提交</el-button
        >
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import { handleApiResponse } from "@/utils/request.js";
import {
  AiDiagnosisInfo,
  UpdateChecklistAiDiagnosisInfo,
  CreateChecklistDiagnosisInfo,
} from "../../../../../wailsjs/go/api/ReportApi.js";
import DataAnalyseOdOs from "@/components/Flow/DataAnalyseOdOs.vue";

onMounted(() => {
  setTimeout(() => {
    handleChangeAnalyse();
  }, 500);
});

const userStore = useUserStore();
const { checkDetailForm } = storeToRefs(userStore);

const analyseId = ref(null);
const handleChangeAnalyse = () => {
  if (analyseId.value == 1) {
    setStorageWithEvent("refresh_copy_text", {
      text: device_info.value,
    });
  } else if (analyseId.value == 2) {
    setStorageWithEvent("refresh_copy_text", {
      text: ai_result.value,
    });
  } else if (analyseId.value == 3) {
    setStorageWithEvent("refresh_copy_text", {
      text: edit_result.value,
    });
  }
};

let device_info = ref(""); // 设备分析
let ai_result = ref(""); // ai分析
let ai_id = ref("");
let edit_result = ref(""); // 手动分析

const customer_data = ref(""); // 姓名：123 左眼屈光度:1, ....

// 更新设备分析的文本
const updateText = (val) => {
  // console.log("更新设备分析的文本", val);
  if (val.text) {
    if (val.type == "right") {
      if (device_info.value) {
        device_info.value += "\n" + "OD / 右眼:" + val.text + "。";
      } else {
        device_info.value = "OD / 右眼:" + val.text + "。";
      }
    } else {
      if (device_info.value) {
        device_info.value += "\n" + "OS / 左眼:" + val.text + "。";
      } else {
        device_info.value = "OS / 左眼:" + val.text + "。";
      }
    }

    userStore.updateDeviceInfo(device_info.value);
  }
};

// 替换掉文本里面的中括号{}
const replaceBrackets = (title, text) => {
  return text
    .replace(/^\{|\}$/g, "")
    .replace(title + "：", "")
    .replace(title + ":", "");
};

// 点击使用ai生成内容
const handleCreateUseAiResult = () => {
  // return console.log({
  //   checklistId: checkDetailForm.value.id,
  //   content: customer_data.value,
  //   questionType: "分析及建议",
  // });

  const loading = ElLoading.service({
    lock: true,
    text: "生成AI内容中,请稍后...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  handleApiResponse(() =>
    AiDiagnosisInfo({
      checklistId: checkDetailForm.value.id,
      content: customer_data.value,
      questionType: "分析及建议",
    })
  )
    .then((res) => {
      if (res.code == 0) {
        ai_result.value = replaceBrackets(
          "分析及建议",
          res.data.list[0].choices[0].message.content
        );

        ai_id.value = res.data.list[0].id;

        handleApiResponse(() =>
          UpdateChecklistAiDiagnosisInfo({
            UniqueId: res.data.list[0].id,
            isUse: 1,
          })
        )
          .then((res2) => {
            if (res2.code == 0) {
              ElMessage.success("生成并使用成功");
              handleChangeAnalyse();
            }
            loading.close();
          })
          .catch((err2) => {
            loading.close();
          });
      } else {
        loading.close();
      }
    })
    .catch((err) => {
      loading.close();
      ElMessage.info(666, err);
      console.info(err);
    });
};

// 取消使用
const handleCancelUse = () => {
  // return ElMessage.info("敬请期待");
  ElMessageBox.confirm("你确定要清空AI分析内容？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      UpdateChecklistAiDiagnosisInfo({
        UniqueId: ai_id.value,
        isUse: 2,
      })
    ).then((res) => {
      if (res.code == 0) {
        ai_result.value = "";
        ElMessage.success("清空成功");
        handleChangeAnalyse();
      }
    });
  });
};

// 手动提交
async function handleEditSubmit() {
  handleApiResponse(() =>
    CreateChecklistDiagnosisInfo({
      checklistId: checkDetailForm.value.id,
      dataType: "分析及建议",
      list: [
        {
          id: 1,
          name: "分析及建议",
          dataList: [
            {
              id: 1,
              dictLabel: edit_result.value,
            },
          ],
        },
      ],
    })
  ).then((res) => {
    if (res.code == 0) {
      ElMessage.success("提交成功");
      handleChangeAnalyse();
    }
  });
}

async function handleEditRemove() {
  ElMessageBox.confirm("你确定要清空手动分析内容？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then((res) => {
    handleApiResponse(() =>
      CreateChecklistDiagnosisInfo({
        checklistId: checkDetailForm.value.id,
        dataType: "分析及建议",
        list: [
          {
            id: 1,
            name: "分析及建议",
            dataList: [
              {
                id: 1,
                dictLabel: "",
              },
            ],
          },
        ],
      })
    ).then((res) => {
      if (res.code == 0) {
        edit_result.value = "";
        ElMessage.success("清空成功");
        handleChangeAnalyse();
      }
    });
  });
}

let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_region_data", (e) => {
    // device_info.value = [];
    ai_result.value = "";
    edit_result.value = "";

    ai_id.value = e.data.aiid;
    customer_data.value = e.data.customerInfo || "";

    if (e.data.aiResult) {
      ai_result.value = e.data.aiResult
        ? replaceBrackets("", e.data.aiResult)
        : "";

      analyseId.value = 2;
    } else if (e.data.editResult) {
      edit_result.value = e.data.editResult;
      analyseId.value = 3;
    } else {
      analyseId.value = 1;
    }
  });
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});
</script>

<style scoped lang="scss">
</style>